package com.doubao.hardware.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * 硬件服务认证工具类
 * 用于从请求中提取用户信息
 */
@Slf4j
public class HardwareAuthUtils {

    private static final String USER_ID_HEADER = "X-User-ID";
    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";

    // 与网关相同的JWT密钥 - 实际应用中应从配置中心获取
    private static final String SECRET_KEY = "DoubaoAuthServiceJwtSecretKey0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final SecretKey JWT_SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

    /**
     * 从请求中获取用户ID
     * 首先尝试从X-User-ID头获取，如果没有则尝试从JWT Token中解析
     *
     * @param request HTTP请求
     * @return 用户ID，如果未找到则返回null
     */
    public static Long getUserIdFromRequest(HttpServletRequest request) {
        // 1. 尝试从X-User-ID头获取
        String userIdHeader = request.getHeader(USER_ID_HEADER);
        if (StringUtils.hasText(userIdHeader)) {
            try {
                return Long.valueOf(userIdHeader);
            } catch (NumberFormatException e) {
                log.warn("无法解析X-User-ID头: {}", userIdHeader, e);
            }
        }

        // 2. 尝试从JWT Token中解析
        String authHeader = request.getHeader(AUTH_HEADER);
        if (StringUtils.hasText(authHeader) && authHeader.startsWith(BEARER_PREFIX)) {
            String token = authHeader.substring(BEARER_PREFIX.length());
            return getUserIdFromToken(token);
        }

        return null;
    }

    /**
     * 从JWT Token中解析用户ID
     *
     * @param token JWT Token
     * @return 用户ID，如果解析失败则返回null
     */
    public static Long getUserIdFromToken(String token) {
        if (!StringUtils.hasText(token)) {
            return null;
        }

        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(JWT_SECRET_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            // 从claims中获取userId
            if (claims.containsKey("userId")) {
                String userIdStr = claims.get("userId", String.class);
                if (StringUtils.hasText(userIdStr)) {
                    return Long.valueOf(userIdStr);
                }
            }

            // 如果没有userId字段，尝试从subject中获取（根据实际JWT结构调整）
            String subject = claims.getSubject();
            if (StringUtils.hasText(subject) && subject.startsWith("user_")) {
                try {
                    return Long.valueOf(subject.substring(5));
                } catch (NumberFormatException e) {
                    log.warn("无法从subject解析用户ID: {}", subject, e);
                }
            }
        } catch (Exception e) {
            log.error("解析JWT令牌失败: {}", e.getMessage(), e);
        }

        return null;
    }

    /**
     * 检查请求是否已认证（是否包含有效的用户ID）
     *
     * @param request HTTP请求
     * @return 是否已认证
     */
    public static boolean isAuthenticated(HttpServletRequest request) {
        return getUserIdFromRequest(request) != null;
    }
}